﻿using KBWebApi.Common;
using KBWebApi.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace KBWebApi.Dal
{
    public class ProductDal
    {
        private static SqlSugarScope db = SqlDBHelper.SqlHelper.GetDB();

        public static bool IsExists(ProductModel product)
        {
            try
            {
                bool isexists = db.Queryable<ProductModel>().Any(t => t.XS_ProductId == product.XS_ProductId);
                return isexists;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("Product.IsExists=>" + ex.ToString());
                return false;
            }
        }

        public int NewKBInput(ProductModel product)
        {
            int count = db.Insertable(product).ExecuteCommand();
            return count;
        }

        public int Update(ProductModel product)
        {
            int count = db.Updateable(product).IgnoreColumns(t => new { t.CreateDate }).ExecuteCommand();
            return count;
        }

        public int Delete(string ProductId)
        {
            int count = db.Deleteable<ProductModel>().Where(t => t.XS_ProductId == int.Parse(ProductId)).ExecuteCommand();
            return count;
        }

        public static DataTable GetAllList(ProductModel product)
        {
            return db.Queryable<ProductModel>()
            .WhereIF(product != null && !string.IsNullOrEmpty(product.ProductNo), t => t.ProductNo.Contains(product.ProductNo))
            .WhereIF(product != null && !string.IsNullOrEmpty(product.ProductDesc), t => t.ProductDesc.Contains(product.ProductDesc))
            .With(SqlWith.NoLock)
            .OrderBy(t => new { t.XS_ProductId, t.ProductNo })
            .ToDataTable();
        }
    }
}
